package com.example.core.utils;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class ReflectionKit {

    public static Class getSuperClassGenricType(final Class clazz, final int index) {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        if (index >= params.length || index < 0) {
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            return Object.class;
        }
        return (Class) params[index];
    }

    public static Object getCascadePropertyValue(Object object, String propertyName) throws Exception {
        if (object == null || propertyName == null || propertyName.isEmpty()) {
            return null;
        }
        Object propertyValue = null;
        String[] propertyNames = propertyName.split("\\.");
        if (propertyNames.length == 1) {
            Field field = ReflectionUtils.findField(object.getClass(), propertyName);
            field.setAccessible(true);
            propertyValue = field.get(object);
        } else {
            String cascadePropertyName = propertyNames[0];
            Field field = object.getClass().getDeclaredField(cascadePropertyName);
            field.setAccessible(true);
            Object cascadePropertyValue = field.get(object);
            if (cascadePropertyValue != null) {
                String subPropertyName = propertyName.substring(cascadePropertyName.length() + 1);
                propertyValue = getCascadePropertyValue(cascadePropertyValue, subPropertyName);
            }
        }
        return propertyValue;
    }
}
